import * as jwt from 'jsonwebtoken';
import type { CacheUser } from '@/typings/global';

const verifyToken = (token: string, secret: string) => {
  return new Promise<false | CacheUser>((resolve) => {
    jwt.verify(token, secret, (errors, data) => {
      if (errors) return resolve(false);
      resolve(data as CacheUser);
    });
  })
}

export const verifyRefreshToken = (token: string) => {
  const secret = process.env.REFRESH_TOKEN_SECRET;
  return verifyToken(token, secret);
}

export const verifyAccessToken = (token: string) => {
  const secret = process.env.ACCESS_TOEN_SECRET;
  return verifyToken(token, secret);
}

export const decodeToken = (token: string) => {
  return jwt.decode(token) as CacheUser;
}